package com.lanyou.cook.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.curator.framework.recipes.queue.DistributedDelayQueue;
import org.apache.curator.framework.recipes.queue.QueueBuilder;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.InterfaceSchedule;
import com.lanyou.cook.repository.InterfaceScheduleRepository;
import com.lanyou.cook.util.ExcelUtil;
import com.lanyou.cook.util.curator.JsonElementSerializer;

@Service
public class InterfaceScheduleService {
	@Autowired
	private CuratorService curatorService;
	@Autowired
	private InterfaceScheduleRepository interfaceScheduleRepository;
	@Autowired 
	private RunningInterfaceWatcher runningInterfaceWatcher;
	
	private DistributedDelayQueue<JsonElement> distributedDelayQueue;
	
	private static final int NOTIFY_MSG_DELAY_MS = 5 * 1000;
	
	private static final FastDateFormat  fastDateFormat = FastDateFormat.getInstance(Constants.DATETIME_PATTERN_2);
	
	@PostConstruct
	private void init() throws Exception{
		initQueue();
	}
	
	@PreDestroy
	private void close(){
		closeQueue();
	}
	
	private void initQueue() throws Exception{
		if(!curatorService.isEnable())
			return;
		QueueBuilder<JsonElement> builder = QueueBuilder.builder(curatorService.getClient(), null, new JsonElementSerializer(Constants.DEFAULT_CHARSET), Constants.ZOOKEPPER_PATH_CHANGED_SCHEDULE);
		distributedDelayQueue = builder.buildDelayQueue();
		distributedDelayQueue.start();
	}
	
	private void closeQueue(){
		if(distributedDelayQueue != null){
			try {
				distributedDelayQueue.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			distributedDelayQueue = null;
		}
	}
	
	public boolean checkIsCanDelete(String interfaceScheduleId) {
		InterfaceSchedule interfaceSchedule = interfaceScheduleRepository.findOne(InterfaceSchedule.idSpecification(interfaceScheduleId));
		boolean isRunning = runningInterfaceWatcher.isRunning(interfaceSchedule.getSystemInterface().getId());
		return !isRunning;
	}
	
	// 通知调度器，某个接口调度已修改
	public void notifyChanged(String interfaceScheduleId) throws Exception{
		if(StringUtils.isBlank(interfaceScheduleId))
			return;
		if(distributedDelayQueue == null)
			return;
		JsonObject msg = new JsonObject();
		msg.addProperty("interfaceScheduleId", interfaceScheduleId);
		msg.addProperty("changeTime", fastDateFormat.format(new Date()));
		
		// 消息延时一段时间，等待数据库事务提交
		distributedDelayQueue.put(msg, System.currentTimeMillis() + NOTIFY_MSG_DELAY_MS);
	}
	public void exportExcel(List<InterfaceSchedule> interfaceSchedules, HSSFWorkbook workbook){
		ExcelUtil.exportUserExcel(interfaceSchedules, workbook);
	}
	
}
